package com.gxg.newdemo1.mynewdamo1.channel.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.view.WindowManager;


/**
 * 字符串操作工具包
 * 
 * @author Luki
 * @version 1.0
 * @created 2012-3-21
 */
public class StringUtils {
	private final static Pattern emailer = Pattern
			.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	private final static SimpleDateFormat dateFormater = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private final static SimpleDateFormat dateFormater2 = new SimpleDateFormat(
			"yyyy-MM-dd");
	private final static SimpleDateFormat dateFormater3 = new SimpleDateFormat(
			"HH:mm");

	/**
	 * 根据时间获取时间戳
	 * 
	 * @param time
	 * @return
	 */
	public static long GetTimeInMillis(String time) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = format.parse(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date.getTime();
	}

	/**
	 * 获取系统当前时间戳
	 */
	public static long getCurrentMillis() {
		return System.currentTimeMillis();
	}

	/**
	 * 将字符串转位日期类型
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		try {
			return dateFormater.parse(sdate);
		} catch (ParseException e) {
			try {
				return dateFormater.parse(new Date(toLong(sdate)).toString());
			} catch (ParseException e1) {
				return null;
			}
		}
	}

	/**
	 * 以友好的方式显示时间
	 * 
	 * @param sdate
	 * @return
	 */
	public static String friendly_time(String sdate) {
		Calendar post = Calendar.getInstance();
		post.setTimeInMillis(toLong(sdate));

		Date time = post.getTime();

		String ftime = "";
		Calendar cal = Calendar.getInstance();

		// 判断是否是同一天
		String curDate = dateFormater2.format(cal.getTime());
		String paramDate = dateFormater2.format(time);
		if (curDate.equals(paramDate)) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max(
						(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
						+ "分钟前";
			else
				ftime = hour + "小时前";
			return ftime;
		}

		long lt = time.getTime() / 86400000;
		long ct = cal.getTimeInMillis() / 86400000;
		int days = (int) (ct - lt);
		if (days == 0) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max(
						(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
						+ "分钟前";
			else
				ftime = hour + "小时前";
		} else if (days == 1) {
			ftime = "昨天" + dateFormater3.format(time);
		} else if (days == 2) {
			ftime = "前天" + dateFormater3.format(time);
		} else if (days > 2 && days <= 10) {
			ftime = days + "天前";
		} else if (days > 10) {
			ftime = dateFormater2.format(time);
		}
		return ftime;
	}

	public static String friendly_num(String str) {
		return friendly_num(toLong(str));
	}

	public static String friendly_num(long l) {
		if (l < 100)
			return l + "";
		else if (l < 1000)
			return l / 100 + "百";
		else if (l < 10000)
			return l / 1000 + "千";
		else if (l < 1000000)
			return l / 10000 + "万";
		else
			return "百万之上";
	}

	/**
	 * 判断给定字符串时间是否为今日
	 * 
	 * @param sdate
	 * @return boolean
	 */
	public static boolean isToday(String sdate) {
		boolean b = false;
		Date time = toDate(sdate);
		Date today = new Date();
		if (time != null) {
			String nowDate = dateFormater2.format(today);
			String timeDate = dateFormater2.format(time);
			if (nowDate.equals(timeDate)) {
				b = true;
			}
		}
		return b;
	}

	/**
	 * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
	 * 
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty(String input) {
		if (input == null || "".equals(input))
			return true;

		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (email == null || email.trim().length() == 0)
			return false;
		return emailer.matcher(email).matches();
	}

	/**
	 * 字符串转整数
	 * 
	 * @param str
	 * @param defValue
	 * @return
	 */
	public static int toInt(String str, int defValue) {
		try {
			return Integer.parseInt(str.replace("+", ""));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return defValue;
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static int toInt(Object obj) {
		if (obj == null)
			return 0;
		return toInt(obj.toString(), 0);
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static long toLong(String obj) {
		try {
			return Long.parseLong(obj);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * 字符串转布尔值
	 * 
	 * @param b
	 * @return 转换异常返回 false
	 */
	public static boolean toBool(String b) {
		try {
			return Boolean.parseBoolean(b);
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * HTML化字符串
	 * 
	 * @param str
	 * @return
	 */
	public static Spanned fromHtml(String str) {
		if (!isEmpty(str)) {
			return Html.fromHtml(str);
		} else
			return Html.fromHtml("");
	}

	/**
	 * 判断两个字符串是否相等
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static boolean isEquals(String a, String b) {
		return a == b || a != null && a.equals(b);
	}

	public static boolean isEmptyOrNull(String value) {
		if (value == null || "".equals(value))
			return true;
		else
			return false;
	}

	/**
	 * 删除input字符串中的html格式
	 * 
	 * @param input
	 * @param length
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	/***
	 * 判断是不是手机号码或者座机
	 * 
	 * @param phoneNumber
	 * @return
	 */
	public static boolean isPhoneNumberValid(String phoneNumber) {
		boolean isValid = false;

		String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
		CharSequence inputStr = phoneNumber;

		Pattern pattern = Pattern.compile(expression);

		Matcher matcher = pattern.matcher(inputStr);

		if (matcher.matches()) {
			isValid = true;
		}

		return isValid;

	}

	/***
	 * 判断是不是手机号码
	 * 
	 * @param phoneNumber
	 * @return
	 */
	public static boolean isPhoneNumberValid2(String phoneNumber) {
		Pattern p = Pattern
				.compile("^((1[3-9][0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(phoneNumber);
		System.out.println(m.matches() + "---");
		return m.matches();
	}

	/**
	 * 判断字符串是否是11位以1开头的数字
	 * 
	 * @param phoneNumber
	 * @return
	 */
	public static boolean isPhoneNum(String phoneNumber) {
		boolean isPhone=false;
		if (phoneNumber.startsWith("1")&&phoneNumber.length() == 11) {
			isPhone = true;
		}else {
			isPhone = false;
		}
		return isPhone;
//		Pattern p = Pattern.compile("1\\d{10}");
//		Matcher m = p.matcher(phoneNumber);
//		return m.matches();
	}

	/**
	 * 判断字符串是否数字
	 * 
	 * @param phoneNumber
	 * @return
	 */
	public static boolean isNumber(String number) {
		Pattern p = Pattern.compile("[1-9][0-9]");
		Matcher m = p.matcher(number);
		return m.matches();
	}

	/**
	 * 判断是否为null或空值
	 * 
	 * @param str
	 *            String
	 * @return true or false
	 */
	public static boolean isNullOrEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	public static double mul(double d1, double d2) { // 进行乘法运算
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 随机获取4位数字
	 * 
	 * @return
	 */
	public static String GetRandomNum() {
		String fourRandom = "";
		// 产生4位的随机数(不足4位前加零)
		int randomNum = (int) (Math.random() * 10000);
		fourRandom = randomNum + "";
		int randLength = fourRandom.length();
		if (randLength < 4) {
			for (int i = 1; i <= 4 - randLength; i++)
				fourRandom = fourRandom + "0";
		}
		return fourRandom;
	}

	public static int getScreenWidth(Activity c) {
		DisplayMetrics dm = new DisplayMetrics();
		c.getWindowManager().getDefaultDisplay().getMetrics(dm);

		int screenWidth = dm.widthPixels;

		return screenWidth;
	}

	public static int getScreenHeight(Activity c) {
		DisplayMetrics dm = new DisplayMetrics();
		c.getWindowManager().getDefaultDisplay().getMetrics(dm);

		int screenHeigh = dm.heightPixels;

		return screenHeigh;
	}

	/**
	 * 获得屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.widthPixels;
	}

	/**
	 * 获得屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.heightPixels;
	}

	public static String StringData() {
		final Calendar c = Calendar.getInstance();
		c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
//		String mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
//		String mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
//		String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
		Date today = new Date();
		String str_date = dateFormater2.format(today);
		String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
		if ("1".equals(mWay)) {
			mWay = "天";
		} else if ("2".equals(mWay)) {
			mWay = "一";
		} else if ("3".equals(mWay)) {
			mWay = "二";
		} else if ("4".equals(mWay)) {
			mWay = "三";
		} else if ("5".equals(mWay)) {
			mWay = "四";
		} else if ("6".equals(mWay)) {
			mWay = "五";
		} else if ("7".equals(mWay)) {
			mWay = "六";
		}
//		yyyy-mm-dd
		String str = str_date + "" + "\t星期" + mWay;
//		String str = mYear + "-" + mMonth + "-" + mDay;

		return str;
	}

	/**
	 * 验证输入身份证号
	 * 
	 * @param 待验证的字符串
	 * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
	 */
	public static boolean IsIdCard(String idcard) {
		// Pattern p =
		// Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
		Pattern p = Pattern.compile("(\\d{17}[0-9a-zA-Z])");
		Matcher m = p.matcher(idcard);
		return m.matches();
	}

	/**
	 * 获取手机IMEI
	 */
	public static String GetPhoneIMEI(Context mContext) {
		TelephonyManager telephonyManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = telephonyManager.getDeviceId();

		return imei;
	}

	/**
	 * 编码URL中的汉字（UTF-8）
	 * 
	 * @param s
	 * @return
	 */
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = String.valueOf(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString().replace(" ", "%20");
	}

	public static final long getBeiJingTime() throws IOException {
		java.util.Locale locale = java.util.Locale.CHINA; // 这是获得本地中国时区
		String pattern = "yyyy-MM-dd HH:mm:ss";// 这是日期格式
		SimpleDateFormat df = new SimpleDateFormat(pattern,
				locale);// 设定日期格式

		URL url = new URL("http://www.bjtime.cn");// 取得资源对象
		URLConnection uc = url.openConnection();// 生成连接对象
		uc.connect(); // 发出连接
		long ld = uc.getDate(); // 取得网站日期时间
		Date date = new Date(ld); // 转换为标准时间对象
		// 分别取得时间中的小时，分钟和秒，并输出
		System.out.print(date.getTime() + "----" + System.currentTimeMillis());

		return date.getTime();
	}


}